﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using myMvcBlog.Models;

namespace myMvcBlog.Controllers
{
    public class TagController : BaseController
    {
        //
        // GET: /Tag/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult View(string nicename, int? page)
        {
            var posts = (from p in Post.All()
                         join pt in PostTag.All() on p.ID equals pt.PostID
                         join t in Tag.All() on pt.TagID equals t.ID
                         where t.UrlName == nicename
                         select p).OrderByDescending(p => p.PostedTime);

            ListView<Post> lvTag = new ListView<Post>();
            lvTag.Title = string.Format("标签：{0}", nicename);
            lvTag.List = posts.Skip(page ?? 0 * ItemsPerPage).Take(ItemsPerPage).ToList();

            lvTag.Pager = new PagerView()
            {
                ControllerName = "Tag",
                ActionName = "View",
                CurrentPage = page ?? 1,
                PageCount = (int)Math.Ceiling((double)posts.Count() / ItemsPerPage)
            };

            return View(lvTag);
        }

        [Authorize]
        public ActionResult DeletePostTag(long postId, long tagId)
        {
            PostTag postTag = PostTag.SingleOrDefault(pt => pt.PostID == postId && pt.TagID == tagId);

            postTag.Delete();

            return null;
        }

        [Authorize]
        public ActionResult AddPostTag(string addtags, long postId)
        {
            string[] tags = addtags.Split(';');
            foreach (string tag in tags)
            {
                Tag t = Tag.SingleOrDefault(ta => ta.Name == tag);
                if (t == null || t.ID == 0)
                {
                    t = new Tag();
                    t.Name = tag;
                    t.UrlName = Server.HtmlEncode(tag);
                    t.IsActive = true;

                    t.Save();
                }

                PostTag pt = new PostTag()
                {
                    PostID = postId,
                    TagID = t.ID
                };

                pt.Save();
            }

            return null;
        }
    }
}
